package com.vim.modules.configServer.controller;

import com.github.pagehelper.PageInfo;
import com.netflix.discovery.EurekaClient;
import com.vim.common.base.BaseController;
import com.vim.modules.configServer.model.Config;
import com.vim.modules.configServer.service.ConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
* @作者 Administrator
* @时间 2019-09-19 10:55:47
* @版本 1.0
* @说明
*/
@Controller
@RequestMapping(value = "/configServer")
public class ConfigController extends BaseController{

    @Autowired
    private ConfigService configService;
    @Autowired
    private EurekaClient eurekaClient;

    /**
    * 列表页面
    */
    @RequiresPermissions(value = "configServer:config:list")
    @RequestMapping(value = {"", "/list"})
    public String list(Model model){
        model.addAttribute("applications", eurekaClient.getApplications().getRegisteredApplications());
        return "configServer/config/list";
    }

    /**
    * 列表数据
    */
    @RequiresPermissions(value = "configServer:config:list")
    @RequestMapping(value = "/dataList")
    @ResponseBody
    public PageInfo<Config> dataList(Config config){
        return configService.findPageList(config.getPageNum(), config.getPageSize(), config);
    }

    /**
     * 编辑页面
     */
    @RequiresPermissions(value = "configServer:config:form")
    @RequestMapping(value = "/form")
    public String form(Config config, Model model){
        model.addAttribute("config", StringUtils.isNoneBlank(config.getId()) ? configService.get(config.getId()) : new Config());
        return "configServer/config/form";
    }

    /**
     * 更新数据
     */
    @RequiresPermissions(value = "configServer:config:form")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> save(Config config){
        Map<String, Object> result = configService.saveOrUpdate(config);
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * 推送配置
     */
    @RequiresPermissions(value = "configServer:config:send")
    @RequestMapping(value = "/sendConfig", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> sendConfig(Config config){
        configService.sendConfig(config.getId());
        return new ResponseEntity<>(success(), HttpStatus.OK);
    }
}